class NewsReporter {
    constructor() {
        this.initializeElements();
        this.bindEvents();
        this.isLoading = false;
    }

    initializeElements() {
        this.urlInput = document.getElementById('newsUrl');
        this.fetchBtn = document.getElementById('fetchNewsBtn');
        this.loadingContainer = document.getElementById('loadingContainer');
        this.newsContent = document.getElementById('newsContent');
        this.errorMessage = document.getElementById('errorMessage');
        this.newsText = document.getElementById('newsText');
        this.timestamp = document.getElementById('timestamp');
        this.newsSource = document.getElementById('newsSource');
        this.totalTokens = document.getElementById('totalTokens');
        this.responseTime = document.getElementById('responseTime');
        this.retryBtn = document.getElementById('retryBtn');
    }

    bindEvents() {
        this.fetchBtn.addEventListener('click', () => this.fetchNews());
        this.retryBtn.addEventListener('click', () => this.fetchNews());
        this.urlInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.fetchNews();
            }
        });

        // 输入框动效
        this.urlInput.addEventListener('focus', () => {
            this.urlInput.parentElement.style.transform = 'scale(1.02)';
        });

        this.urlInput.addEventListener('blur', () => {
            this.urlInput.parentElement.style.transform = 'scale(1)';
        });
    }

    async fetchNews() {
        if (this.isLoading) return;

        const newsUrl = this.urlInput.value.trim();
        if (!newsUrl) {
            this.showError('请输入有效的新闻网址');
            return;
        }

        if (!this.isValidUrl(newsUrl)) {
            this.showError('请输入正确格式的网址');
            return;
        }

        this.startLoading();
        const startTime = Date.now();

        try {
            const response = await fetch('/api/news', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ newsUrl })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            const endTime = Date.now();
            const responseTime = ((endTime - startTime) / 1000).toFixed(2);

            this.displayNews(data, newsUrl, responseTime);
        } catch (error) {
            console.error('获取新闻失败:', error);
            this.showError('获取新闻失败，请检查网址或稍后重试');
        } finally {
            this.stopLoading();
        }
    }

    startLoading() {
        this.isLoading = true;
        this.fetchBtn.disabled = true;
        
        // 隐藏其他内容
        this.hideAllSections();
        
        // 显示加载动画
        this.loadingContainer.style.display = 'flex';
        
        // 按钮状态变化
        const buttonText = this.fetchBtn.querySelector('.button-text');
        buttonText.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 获取中...';
        
        // 添加加载动效到按钮
        this.fetchBtn.style.background = 'linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%)';
    }

    stopLoading() {
        this.isLoading = false;
        this.fetchBtn.disabled = false;
        
        // 恢复按钮状态
        const buttonText = this.fetchBtn.querySelector('.button-text');
        buttonText.innerHTML = '<i class="fas fa-microphone"></i> 收取播报';
        this.fetchBtn.style.background = 'var(--secondary-gradient)';
        
        // 隐藏加载动画
        this.loadingContainer.style.display = 'none';
    }

    displayNews(data, newsUrl, responseTime) {
        console.log('收到的数据:', data); // 调试日志
        
        if (!data.choices || !data.choices[0] || !data.choices[0].message) {
            this.showError('返回的数据格式不正确');
            return;
        }

        let newsMessage = data.choices[0].message.content;
        
        // 🔑 关键修复：处理数组格式的content
        if (Array.isArray(newsMessage)) {
            // 提取所有type为"text"的内容
            const textContents = newsMessage
                .filter(item => item.type === 'text' && item.text && item.text.content)
                .map(item => item.text.content);
            
            if (textContents.length > 0) {
                newsMessage = textContents.join('\n\n');
            } else {
                // 如果没有text类型的内容，尝试从工具调用中提取摘要
                const toolSummaries = newsMessage
                    .filter(item => item.type === 'tool')
                    .map(item => '工具调用完成，正在分析新闻内容...')
                    .join('\n');
                
                newsMessage = toolSummaries || '已获取新闻数据，正在处理中...';
            }
        }
        
        // 确保是字符串并清理格式
        newsMessage = String(newsMessage || '暂无新闻内容').trim();
        
        // 如果内容仍然是 [object Object]，说明转换失败
        if (newsMessage === '[object Object]') {
            newsMessage = '抱歉，无法正确解析新闻内容。请稍后重试。';
        }
        
        const usage = data.usage || {};

        // 填充新闻内容
        this.timestamp.textContent = new Date().toLocaleString('zh-CN');
        this.newsSource.textContent = this.extractDomain(newsUrl);
        this.totalTokens.textContent = usage.total_tokens || '-';
        this.responseTime.textContent = responseTime;

        // 显示新闻内容
        this.newsContent.style.display = 'block';
        
        // 打字机效果
        this.typewriterEffect(newsMessage);
    }

    typewriterEffect(text) {
        // 确保text是字符串类型
        const textString = String(text || '');
        this.newsText.textContent = '';
        let index = 0;
        const speed = 30; // 打字速度

        const type = () => {
            if (index < textString.length) {
                this.newsText.textContent += textString.charAt(index);
                index++;
                setTimeout(type, speed);
            }
        };

        type();
    }

    showError(message) {
        this.hideAllSections();
        this.errorMessage.style.display = 'block';
        this.errorMessage.querySelector('p').textContent = message;
        
        // 震动效果
        this.errorMessage.style.animation = 'shake 0.5s ease-in-out';
        setTimeout(() => {
            this.errorMessage.style.animation = '';
        }, 500);
    }

    hideAllSections() {
        this.loadingContainer.style.display = 'none';
        this.newsContent.style.display = 'none';
        this.errorMessage.style.display = 'none';
    }

    isValidUrl(string) {
        try {
            const url = new URL(string);
            return url.protocol === 'http:' || url.protocol === 'https:';
        } catch (_) {
            return false;
        }
    }

    extractDomain(url) {
        try {
            const domain = new URL(url).hostname;
            return domain.replace('www.', '');
        } catch (_) {
            return '未知来源';
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new NewsReporter();
    
    // 添加页面加载动效
    const container = document.querySelector('.container');
    container.style.opacity = '0';
    container.style.transform = 'translateY(20px)';
    
    setTimeout(() => {
        container.style.transition = 'all 0.8s ease-out';
        container.style.opacity = '1';
        container.style.transform = 'translateY(0)';
    }, 100);
}); 